package atom.core0.jvm;

import java.lang.management.ClassLoadingMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryUsage;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

public class JvmUtil
{
	static public MemoryBean getJvmMemory(int flag)
	{
		MemoryUsage mu1 = null;
		try
		{
			if (flag == 1)
				mu1 = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
			else
				mu1 = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();
		}
		catch (Throwable t)
		{
			t.printStackTrace();
		}
		long M1 = 1024 * 1024;
		MemoryBean bean = new MemoryBean();
		if (mu1 != null)
		{
			bean.setCommitted(mu1.getCommitted() / M1);
			bean.setInit(mu1.getInit() / M1);
			bean.setMax(mu1.getMax() / M1);
			bean.setUsed(mu1.getUsed() / M1);
		}
		return bean;
	}

	static public void getJvmRuntime()
	{
		RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
	}

	static public ThreadInfo[] getJvmThread()
	{
		ThreadMXBean bean = ManagementFactory.getThreadMXBean();
		long[] ids = bean.getAllThreadIds();
		ThreadInfo[] info = bean.getThreadInfo(ids);
		return info;
	}

	static public ClassLoadingBean getJvmClassLoading()
	{
		ClassLoadingMXBean mbean = ManagementFactory.getClassLoadingMXBean();
		
		ClassLoadingBean bean = new ClassLoadingBean();
		bean.setLoadedClassCount(mbean.getLoadedClassCount());
		bean.setTotalLoadedClassCount(mbean.getTotalLoadedClassCount());
		bean.setUnloadedLoadedClassCount(mbean.getUnloadedClassCount());
		return bean;
		
	}
	static public void showThreadInfo(ThreadInfo[] info)
	{
		for(int i=0;i<info.length;i++)
		{
			System.out.println("id="+info[i].getThreadId()+",name="+info[i].getThreadName());
		}

	}
}
